<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\CouponList;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\OrderGoods;
use app\common\model\RechargeLog;
use app\common\model\UserCoupon;
use app\common\model\IntegralLog;
use fast\Random;
use think\Validate;
use app\common\model\User as userModel;
use app\common\model\Address;
use app\common\model\Area;
use think\Db;
use think\Loader;
/**
 * 会员接口
 */
class User extends Api
{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605579142",
    "data": {
    "id": 1,
    "username": "哎哟",用户名
    "member_card": "HG0000000001",会员卡号
    "head_image": "/uploads/20201116/6ab9a227a6a626bb227a20c849a93a07.png",头像
    "money": "0.00",余额
    "integral": "0.00",积分
    "coupon_count": 3,优惠券数量
    "gender_text": ""
    }
    })
     */
    public function index()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id,username,member_card,head_image,money,integral')->find();
        //未使用的优惠券查看是否已过期 如果已过期的话把状态改为已过期
        action_coupon();
        //可用优惠券
        $coupon = UserCoupon::where(['userid'=>$user_info['id'],'status'=>0])->count();
        $user_info['coupon_count']= $coupon;
        $this->success($user_info);
    }
    /**
     * 个人资料展示
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": {
    "id": 1,
    "username": "admin",昵称
    "mobile": "13888888888",手机号
    "gender": 0,性别0男1女
    "birthday": 1995-05-13,
    "status_text": ""
    }
    })
     */
    public function profile()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id,username,mobile,gender,birthday')->find();
        $user_info['birthday'] = date('Y-m-d',$user_info['birthday']);
        $this->success($user_info);
    }
    /**
     * 个人资料提交
     * @ApiMethod   (POST)
     * @param string $token TOKEN
     * @param string $username 用户名
     * @param string $mobile 手机号
     * @param string $gender 性别0男1女
     * @param string $birthday 生日
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function profile_submit()
    {
        $token = $this->request->post('token');
        $data['username'] = $this->request->post('username');
        $data['mobile'] = $this->request->post('mobile');
        $data['gender'] = $this->request->post('gender');
        $data['birthday'] = $this->request->post('birthday');
        $user_info = userModel::where('token',$token)->field('id')->find();
        if (!Validate::regex($data['mobile'], "^1\d{10}$")) {
            $this->error('手机格式不正确');
        }
        $data['birthday'] = strtotime($data['birthday']);
        Db::startTrans();
        try {
            $res = userModel::where('id',$user_info['id'])->update($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','修改成功');
        }else{
            $this->error('修改失败');
        }
        $this->success($user_info);
    }
    /**
     * 订单列表
     * @param string $token TOKEN
     * @param string $status 0全部1待付款
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605750309",
    "data": [
    {
    "id": 12,order_id
    "order_sn": "HGJB171987293396",订单号
    "status": 1,状态0未付款1已付款
    "actual_price": "540.00",支付金额
    "goods_list": [商品列表
    {
    "id": 13,
    "order_id": 12,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",商品图片
    "goods_name": "天然零卡糖",商品名称
    "attr_name": "8寸",规格
    "unit_price": "128.00",单价
    "num": 3,数量
    "createtime": 1605619872
    },
    {
    "id": 14,
    "order_id": 12,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",
    "goods_name": "天然零卡糖",
    "attr_name": "4寸",
    "unit_price": "78.00",
    "num": 2,
    "createtime": 1605619872
    }
    ],
    "status_text": "Status 1",
    "paytime_text": "",
    "distribution_type_text": ""
    },
    {
    "id": 11,
    "order_sn": "HGJB171969199515",
    "status": 1,
    "actual_price": "432.00",
    "goods_list": [
    {
    "id": 11,
    "order_id": 11,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",
    "goods_name": "天然零卡糖",
    "attr_name": "8寸",
    "unit_price": "128.00",
    "num": 3,
    "createtime": 1605619691
    },
    {
    "id": 12,
    "order_id": 11,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",
    "goods_name": "天然零卡糖",
    "attr_name": "4寸",
    "unit_price": "78.00",
    "num": 2,
    "createtime": 1605619691
    }
    ],
    "status_text": "Status 1",
    "paytime_text": "",
    "distribution_type_text": ""
    }
    ]
    })
     */
    public function order_list()
    {
        $token = $this->request->get('token');
        $status = $this->request->get('status')==null?0:$this->request->get('status');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id')->find();
        $where['userid'] = array('eq',$user['id']);
        if($status){
            $where['status'] = array('eq',1);
        }
        $list = Order::where($where)->field('id,order_sn,status,actual_price')->order('id desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $order_goods= OrderGoods::where('order_id',$value['id'])->order('id asc')->select();
            foreach($order_goods as &$v1){
                $v1['goods_image'] = $this->domain.$v1['goods_image'];
            }
            $value['goods_list'] = $order_goods;
        }
        $this->success($list);
    }
    /**
     * 订单详情
     * @param string $token TOKEN
     * @param string $order_id 订单ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605750832",
    "data": {
    "id": 12,
    "order_sn": "HGJB171987293396",订单号
    "userid": 1,
    "price": "540.00",总价
    "discounted_price": "0.00",优惠金额
    "actual_price": "540.00",实际支付金额
    "status": 1,状态0未付款1已付款
    "createtime": 2020-11-17 21:31:13",订单时间
    "username": "张三",收货人姓名
    "mobile": "13444444444",电话
    "address": "金钟桥大街23号",地址
    "coupon_id": 0,
    "note": "meishade ",
    "paytype": 1,支付方式0余额支付1微信支付
    "paytime": 1605619873,
    "distribution_type": 0,配送方式0=配送,1=自提
    "deliverytime": "2020-11-20 10:30",配送时间
    "order_goods": [商品列表
    {
    "id": 13,
    "order_id": 12,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",商品图片
    "goods_name": "天然零卡糖",商品名称
    "attr_name": "8寸",规格
    "unit_price": "128.00",单价
    "num": 3,数量
    "createtime": 1605619872
    },
    {
    "id": 14,
    "order_id": 12,
    "goods_image": "http://www.cake.com/uploads/20201116/5268b1414a12bbad4cfb204bc97dd3dd.png",
    "goods_name": "天然零卡糖",
    "attr_name": "4寸",
    "unit_price": "78.00",
    "num": 2,
    "createtime": 1605619872
    }
    ],
    "status_text": "Status 1",
    "paytime_text": "2020-11-17 21:31:13",
    "distribution_type_text": "Distribution_type 0"
    }
    })
     */
    public function order_detail()
    {
        $token = $this->request->get('token');
        $order_id = $this->request->get('order_id');
        $user= userModel::where('token',$token)->field('id')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            $info['createtime'] = date('Y-m-d H:i:s',$info['createtime']);
            $info['deliverytime'] = date('Y-m-d H:i',$info['deliverytime']);
             $order_goods =   OrderGoods::where('order_id',$info['id'])->order('id asc')->select();
            foreach($order_goods as &$v1){
                $v1['goods_image'] = $this->domain.$v1['goods_image'];
            }
            $info['order_goods'] = $order_goods;
            $this->success($info);
        }
        $this->error('订单不存在');
    }
    /**
     * 立即支付
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $order_id 订单ID
     * @ApiReturn   ()
     */
    public function pay_immediately()
    {
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');
        $user= userModel::where('token',$token)->field('id,openid')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            if($info['status'] != 0){
                $this->error('只有未支付的订单才可支付');
            }
            //优惠券
            if($info['coupon_id']){
                $coupon_info = UserCoupon::where(['userid'=>$user['id'],'id'=>$info['coupon_id']])->find();
                if(empty($coupon_info)){
                    $this->error('优惠券不存在');
                }
                if($coupon_info['status'] != 0){
                    $this->error('该优惠券已使用,请重新下单');
                }
            }
            $data['order_sn'] = 'HG'.getOrderSn();
            Db::startTrans();
            try {
                $res = Order::where('id',$info['id'])->update($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$info['actual_price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user['openid'],$this->domain . "/api/response/goods_response");
                $result = json_decode($result,true);
                $this->success($result,'请求成功');
            }
            $this->success('','取消成功');
        }
        $this->error('订单不存在');
    }
    /**
     * 取消订单
     * @param string $token TOKEN
     * @param string $order_id 订单ID
     * @ApiReturn   ()
     */
    public function cancel_order()
    {
        $token = $this->request->get('token');
        $order_id = $this->request->get('order_id');
        $user= userModel::where('token',$token)->field('id')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            if($info['status'] != 0){
                $this->error('只有未支付的订单才可取消');
            }
            $res = Order::where('id',$order_id)->where('userid',$user['id'])->delete();
            $res1 = OrderGoods::where('order_id',$info['id'])->delete();
            $this->success('','取消成功');
        }
        $this->error('订单不存在');
    }
    /**
     * 充值列表
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605596158",
    "data": {
    "money": "0.00",当前用户余额
    "list": [
    {
    "id": 1,充值金额ID
    "money": 300,充值金额
    "give_money": 30赠送金额
    },
    {
    "id": 2,
    "money": 500,
    "give_money": 80
    },
    {
    "id": 3,
    "money": 1000,
    "give_money": 200
    }
    ]
    }
    })
     */
    public function recharge_list()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id,money')->find();
        $list = RechargeLog::order('money asc')->field('id,money,give_money')->select();
        $data = [
            'money'=>$user['money'],
            'list'=>$list
        ];
        $this->success($data);
    }
    /**
     * 立即充值
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $recharge_id 充值金额ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function recharge_now()
    {
        $recharge_id = $this->request->post('recharge_id');
        $token = $this->request->post('token');
        $user = userModel::where('token',$token)->field('id,openid')->find();
        $recharge_info = RechargeLog::where('id',$recharge_id)->find();
        if($recharge_info){
            $data = [
                'order_sn'=>'RE'.getOrderSn(),
                'recharge_id'=>$recharge_info['id'],
                'userid'=>$user['id'],
                'money'=>$recharge_info['money'],
                'give_money'=>$recharge_info['give_money'],
                'createtime'=>time()
            ];
            Db::startTrans();
            try {
                $res = Db::name('recharge_order')->insert($data);
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$data['money'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user['openid'],$this->domain . "/api/response/recharge_response");
                $result = json_decode($result,true);
                //$result['type'] = 1;
                $this->success($result,'请求成功');
            }
        }
    }
    /**
     * 积分记录
     * @param string $token TOKEN
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605341645",
    "data": [
    {
    "id": 3,
    "userid": 1,
    "money": "500.00",数量
    "status": 1,1=消费获得,2=兑换优惠券
    "createtime": "2020-11-14 13:56"时间
    },
    {
    "id": 2,
    "userid": 1,
    "money": "100.00",
    "status": 2,类型:1=消费获得,2=兑换扣除
    "order_id": "2",
    "createtime": "2020-11-11 21:05"
    },
    {
    "id": 1,
    "userid": 1,
    "money": "100.00",
    "status": 1,
    "order_id": "1",
    "createtime": "2020-11-11 21:05"
    }
    ]
    })
     */
    public function integral_log()
    {
        $token = $this->request->get('token');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id,integral')->find();
        $list = IntegralLog::where('userid',$user['id'])->order('id desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d H:i',$value['createtime']);
        }
        $data = [
            'integral'=>$user['integral'],
            'list'=>$user['$list'],
        ];
        $this->success($data);
    }
    /**
     * 余额记录
     * @param string $token TOKEN
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605341645",
    "data": [
    {
    "id": 3,
    "userid": 1,
    "money": "500.00",数量
    "status": 1,1=充值,2=消费
    "createtime": "2020-11-14 13:56"时间
    },
    {
    "id": 2,
    "userid": 1,
    "money": "100.00",
    "status": 2,
    "order_id": "2",
    "createtime": "2020-11-11 21:05"
    },
    {
    "id": 1,
    "userid": 1,
    "money": "100.00",
    "status": 1,
    "order_id": "1",
    "createtime": "2020-11-11 21:05"
    }
    ]
    })
     */
    public function money_log()
    {
        $token = $this->request->get('token');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id')->find();
        $list = MoneyLog::where('userid',$user['id'])->order('id desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d H:i',$value['createtime']);
        }
        $this->success($list);
    }
    /**
     * 兑换优惠券记录
     * @param string $token TOKEN
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605580748",
    "data": [
    {
    "name": "9折券",优惠券名称
    "createtime": "2020-11-16 21:09"兑换时间
    },
    {
    "name": "8折券",
    "createtime": "2020-11-16 21:00"
    }
    ]
    })
     */
    public function exchange_log()
    {
        $token = $this->request->get('token');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id')->find();
        $list = UserCoupon::where('userid',$user['id'])->where('is_exchange',1)->order('id desc')->field('name,createtime')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d H:i',$value['createtime']);
        }
        $this->success($list);
    }
    /**
     * 我的优惠券列表
     * @param string $token TOKEN
     * @param string $status 3全部0已使用1未使用2已过期
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605581304",
    "data": [
    {
    "id": 4,
    "name": "9折券",名称
    "createtime": "2020-11-16 21:09",时间
    "status": 0状态0=未使用,1=已使用,2=已过期
    },
    {
    "id": 3,
    "name": "免邮券",
    "createtime": "2020-11-16 21:06",
    "status": 0
    },
    {
    "id": 1,
    "name": "8折券",
    "createtime": "2020-11-16 21:00",
    "status": 0
    }
    ]
    })
     */
    public function my_coupon_list()
    {
        $token = $this->request->get('token');
        $status  = $this->request->get('status')==null?3:$this->request->get('status');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id')->find();
        //未使用的优惠券查看是否已过期 如果已过期的话把状态改为已过期
        action_coupon();
        $where['userid'] = array('eq',$user['id']);
        if($status != 3){
            $where['status'] = array('eq',$status);
        }
        $list = UserCoupon::where($where)->order('id desc')->field('id,name,createtime,status')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d H:i',$value['createtime']);
        }
        $this->success($list);
    }
    /**
     * 优惠券列表-兑换
     * @param string $token TOKEN
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605582799",
    "data": {
    "list": [
    {
    "id": 4,优惠券ID
    "name": "9折券",名称
    "image": "http://www.cake.com/uploads/20201116/777350c31c1aa78c9195ab8f3197d74b.png",图片
    "status": 0,类型0折扣券1免邮券
    "integral": 500,所需积分
    "status_text": "Status 0"
    },
    {
    "id": 3,
    "name": "免邮券",
    "image": "http://www.cake.com/uploads/20201116/8e5523b86e890989c7a6c7450b2c5ec8.png",
    "status": 1,
    "integral": 500,
    "status_text": "Status 1"
    },
    {
    "id": 1,
    "name": "8折券",
    "image": "http://www.cake.com/uploads/20201116/4a33f0841864f5b5defaa2d20c5a5b9d.png",
    "status": 0,
    "integral": 500,
    "status_text": "Status 0"
    }
    ],
    "integral": "0.00"用户积分
    }
    })
     */
    public function coupon_list()
    {
        $token = $this->request->get('token');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $user = userModel::where('token',$token)->field('id,integral')->find();
        //未使用的优惠券查看是否已过期 如果已过期的话把状态改为已过期
        action_coupon();
        $list = CouponList::order('id desc')->field('id,name,image,status,integral')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['image'] = $this->domain.$value['image'];
        }
        $data = [
            'list'=>$list,
            'integral'=>$user['integral']
        ];
        $this->success($data);
    }
    /**
     * 优惠券详情-兑换
     * @param string $token TOKEN
     * @param string $id 优惠券ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605581966",
    "data": {
    "id": 4,优惠券ID
    "name": "9折券",名称
    "image": "http://www.cake.com/uploads/20201116/777350c31c1aa78c9195ab8f3197d74b.png",图片
    "status": 0,类型0折扣券1免邮券
    "discount": 9,
    "integral": 500,所需积分
    "instructions": "1. 最高可优惠100元<br />\r\n2. 自领取后3个月内有效<br />\r\n3. 优惠券不能叠加使用",兑换说明
    "createtime": 1605532160,
    "expiredtime": 1609430400,
    "status_text": "Status 0"
    }
    })
     */
    public function coupon_detail()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user = userModel::where('token',$token)->field('id')->find();
        $info = CouponList::where('id',$id)->find();
        if($info){
            $info['image'] = $this->domain.$info['image'];
            $info['instructions'] = nl2br($info['instructions']);
        }
        $this->success($info);
    }
    /**
     * 兑换优惠券
     * @ApiMethod   (POST)
     * @param string $coupon_id 优惠券ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function buy_order()
    {
        $token = $this->request->post('token');
        $coupon_id = $this->request->post('coupon_id');
        $user = userModel::where('token',$token)->field('id,integral')->find();
        $info = CouponList::where('id',$coupon_id)->find();
        if(empty($info)){
            $this->error('优惠券不存在');
        }
        //判断用户积分是否足够
        if($info['integral'] >$user['integral']){
            $this->error('您的积分不足');
        }
        $data['userid'] = $user['id'];
        $data['image'] = $info['image'];
        $data['name'] = $info['name'];
        $data['type'] = $info['status'];
        $data['discount'] = $info['discount'];
        $data['expiredtime'] = $info['expiredtime'];
        $data['is_exchange'] = 1;
        Db::startTrans();
        try {
            $res = UserCoupon::create($data);
            if($res){
                $data1 = [
                    'userid'=>$user['id'],
                    'money'=>$info['integral'],
                    'status'=>2,
                ];
                $res1 = IntegralLog::create($data1);
                if($res1){
                    $res2 = userModel::where('id',$user['id'])->setDec('integral',$info['integral']);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res && $res1 && $res2){
            $this->success('','兑换成功');
        }else{
            $this->error('兑换失败');
        }
    }
    /**
     * 收货地址列表
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1600324552",
    "data": [{
    "id": 1,
    "userid": 1,
    "address": "明理路123号",详细地址
    "username": "张三",姓名
    "mobile": "13433333333",手机号
    "createtime": null
    }, {
    "id": 2,
    "userid": 1,
    "address": "明理路123号",
    "username": "张三",
    "mobile": "13433333333",
    "createtime": null
    }]
    })
     */
    public function address_list()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $list =Address::where('userid',$user_info['id'])->order('id desc')->select();
        foreach($list as &$value){
            $province = Area::where('id',$value['province_id'])->value('name');
            $city = Area::where('id',$value['city_id'])->value('name');
            $area = Area::where('id',$value['area_id'])->value('name');
            $value['address'] = $province.$city.$area.$value['address'];
        }
        $this->success($list);
    }
    /**
     * 收货地址添加
     * @ApiMethod   (POST)
     * @param string $username   姓名
     * @param string $mobile 手机号
     * @param string $province_id 省ID
     * @param string $city_id 市ID
     * @param string $area_id 区/县ID
     * @param string $address 详细地址
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function insert_address()
    {
        $token = $this->request->post('token');
        $data['username'] = $this->request->post('username');
        $data['mobile'] = $this->request->post('mobile');
        $data['province_id'] = $this->request->post('province_id');
        $data['city_id'] = $this->request->post('city_id');
        $data['area_id'] = $this->request->post('area_id');
        $data['address'] = $this->request->post('address');
        $user = userModel::where('token',$token)->field('id')->find();
        if (!Validate::regex($data['mobile'], "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $this->shelis($data);
        Db::startTrans();
        try {
            $data['userid']=$user['id'];
            $res = Address::create($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    /**
     * 收货地址编辑显示页面
     * @param string $id   收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1600325130",
    "data": {
    "id": 1,
    "userid": 1,
    "area": "河南省郑州市金水区",省市区
    "address": "明理路123号",详细地址
    "username": "张三",姓名
    "mobile": "13433333333",手机号
    "createtime": null
    }
    })
     */
    public function address_info()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user = userModel::where('token',$token)->field('id')->find();
        $info = Address::where(['userid'=>$user['id'],'id'=>$id])->find();
        if(empty($info)){
            $this->error('数据异常');
        }
        $info['province'] = Area::where('id',$info['province_id'])->value('name');
        $info['city'] = Area::where('id',$info['city_id'])->value('name');
        $info['area'] = Area::where('id',$info['area_id'])->value('name');
        //$info['area'] = $province.$city.$area;
        $this->success($info);

    }
    /**
     * 收货地址修改提交
     * @ApiMethod   (POST)
     * @param string $username   姓名
     * @param string $mobile 手机号
     * @param string $province_id 省ID
     * @param string $city_id 市ID
     * @param string $area_id 区/县ID
     * @param string $address 详细地址
     * @param string $id 收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function edit_address()
    {
        $data['username'] = $this->request->post('username');
        $data['mobile'] = $this->request->post('mobile');
        $data['province_id'] = $this->request->post('province_id');
        $data['city_id'] = $this->request->post('city_id');
        $data['area_id'] = $this->request->post('area_id');
        $data['address'] = $this->request->post('address');
        //$data['gender'] = $this->request->post('gender');
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user = userModel::where('token',$token)->field('id')->find();
        if (!Validate::regex($data['mobile'], "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $this->shelis($data);
        Db::startTrans();
        try {
            $res = Address::where('id',$id)->update($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 收货地址删除
     * @ApiMethod   (POST)
     * @param string $id 收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function delete_address()
    {

        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user = userModel::where('token',$token)->field('id')->find();
        $info = Address::where(['id'=>$id,'userid'=>$user['id']])->find();
        if($info){
            Db::startTrans();
            try {
                $res = Address::where('id',$id)->delete();
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('','删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        $this->error('数据异常');
    }
    private function shelis($data){
        $rule = [
            'username'  => 'require',
            'mobile'  => 'require',
            'province_id'  => 'require',
            'city_id'  => 'require',
            'area_id'  => 'require',
            'address'  => 'require',
        ];
        $msg = [
            'username.require'  => '请填写联系人姓名',
            'mobile.require'  => '请填写手机号',
            'province_id.require'  => '请选择省',
            'city_id.require'  => '请选择市',
            'area_id.require'  => '请选择区/县',
            'address.require'  => '请填写详细地址',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
    }
    /**
     * 获取手机号
     * @ApiMethod   (POST)
     * @param int $token 用户token
     * @param char $js_code code
     * @param char $encryptedData encryptedData
     * @param char $iv iv
     *  @ApiReturn   ({
    "code": "200",
    "msg": "登录成功",
    })
     **/
    public function getmobile()
    {
        $iv = $this->request->post('iv');
        $js_code = $this->request->post('js_code');
        $encryptedData = $this->request->post('encryptedData');
        $token = $this->request->post('token');
        $user= userModel::where('token',$token)->field('id')->find();
        Loader::import('wxpay.wxBizDataCrypt', EXTEND_PATH, '.php');
        $appid = 'wx7496026fb84d3edf';
        $appsecret = '2f8b284476159fd09bc501a16f627dc6';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $js_code . '&grant_type=authorization_code';
        $data = "";
        $arr = $this->vget($url);  // 一个使用curl实现的get方法请求
        $arr = json_decode($arr, true);
        if ($arr) {
            if(isset($arr['errcode'])){
                $this->error($arr['errmsg']);
            }
            $pc = new \WXBizDataCrypt($appid, $arr['session_key']);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );
            if ($errCode == 0) {
                $data= json_decode($data,true);
            } else {
                $this->error('获取失败');
            }
            $phone =$data['phoneNumber'];
            $res = userModel::where('token',$token)->update(['mobile'=>$phone]);
            $this->success('','请求成功');
        } else {
            $this->error('网络请求失败');
        }
    }
    public function vget($url){
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }
}
